package whf.framework.web.struts.converters;

import java.sql.Date;
import java.sql.Timestamp;

import org.apache.commons.beanutils.ConversionException;

import whf.framework.util.DateUtils;

/**
 * @author wanghaifeng
 * @create Dec 26, 2006 2:44:30 PM
 * 
 */
public class SqlDateConverter extends AbstractConverter {

	public SqlDateConverter(Date defaultValue) {
		super(true, defaultValue);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.apache.commons.beanutils.Converter#convert(java.lang.Class, java.lang.Object)
	 */
	public Object convert(Class type, Object value) {
		if (value == null || "".equals(value)) {
			if (useDefault) {
				return (defaultValue);
			} else {
				throw new ConversionException("No value specified");
			}
		}

		if (value instanceof Date) {
			return (value);
		}

		try {
			if(type == Timestamp.class){
				return DateUtils.parseDatetime(value.toString());
			} else {
				return (Date.valueOf(value.toString()));
			}
		} catch (Exception e) {
			if (useDefault) {
				return (defaultValue);
			} else {
				throw new ConversionException(e);
			}
		}
	}

}
